<script lang="ts" setup>
import {reactive, ref, onMounted} from 'vue'
import {FormRules, ElMessage, ElMessageBox} from 'element-plus';
import {useRouter, useRoute} from 'vue-router';
import {userInsert, userUpdate, userInfo, userSendMessage} from '@/api/system/user';
import {useValidator} from '@/hooks/web/useValidator';
import {useCommonRequest} from '@/hooks/web/useCommonRequest';
import {usePermissions} from "@/hooks/web/usePermissions";
import {useCommon} from "@/hooks/web/useCommon";

const {gatherOptions, optionsBox} = useCommon()
let {roleData, getRoleData} = useCommonRequest()
const {isAdmin} = usePermissions();
getRoleData()
const {phoneValid, required, emailValid} = useValidator()
const router = useRouter()
const route = useRoute()
const marketRole = ref('')
interface ruleForm {
  username: string,
  password: string,
  phone: string,
  realname: string,
}

let resLoading = ref(false)
let loading = ref(false)
let validatePhone = (rule: any, value: any, callback: any) => {
  phoneValid(value, callback)
}

let validateEmail = (rule: any, value: any, callback: any) => {
  emailValid(value, callback)
}

const isMarketRole = () => {
  marketRole.value = form.role_id.find(item => {
    return item == 4
  })
}

const handleRoles = () => {
  isMarketRole()
}


const rules = reactive<FormRules<ruleForm>>({
  username: [required('请输入账号')],
  password: [{required: true, message: '请输入密码', trigger: 'blur'}],
  phone: [{required: true, validator: validatePhone, trigger: 'blur'}],
  email: [{required: false, validator: validateEmail, trigger: 'blur'}],
  realname: [required('请输入真实姓名')],
})

let form = reactive({
  id: '',
  username: '',
  password: '',
  phone: '',
  realname: '',
  role_id: '',
  email: '',
  qr_url: '',
  att_id: '',
  channel_ids:'',
})

let timer = ref(null)

let formRef = ref(null)
let userId = ref(null)
let routeType = ref(null)

const onSubmit = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      let res = ''
      loading.value = true
      if (userId.value) {
        form.id = userId.value
        res = await userUpdate(form)
      } else {
        res = await userInsert(form)
      }
      loading.value = false
      if (res) {
        ElMessage({message: '操作成功', type: 'success'})
        goBack()
      }
    } else {
      return
    }
  })
}

const pollingFetch = () => {
  clearInterval(timer.value)
  timer.value = setInterval(async () => {
    let result = await userInfo({id: userId.value});
    console.log(result);
    if (!result.data.qr_url) {
      form.qr_url = ''
      form.att_id = result.data.att_id
      clearInterval(timer.value)
    }
  }, 3000)
}

const handleSendMessage = async () => {
  let data = {
    uid: userId.value
  }
  const response = await userSendMessage(data)
  if (response) {
    ElMessage({message: '发送成功', type: 'success'})
  }
}

const handleUnbundle = () => {
  ElMessageBox.confirm('请确认是否解绑 ? ', '提示', {type: 'warning'}).then(async () => {
    let data = {
      id: userId.value,
      att_id: 0
    }
    let res = await userUpdate(data)
    if (res) {
      ElMessage({message: '解绑成功', type: 'success'})
      await getUser()
    }
  }).catch(() => {
  })
}

const goBack = () => {
  router.push('/system/user')
}

const getUser = async () => {
  resLoading.value = true
  let result = await userInfo({id: userId.value});
  resLoading.value = false
  if (result) {
    if (result.data.qr_url) {
      pollingFetch()
    }
    form = Object.assign(form, result.data)
    await isMarketRole()
  }
}

onMounted(() => {
  gatherOptions()
  if (route.query.userId) {
    routeType.value = route.query.type
    userId.value = route.query.userId
    getUser()
  }
})

onBeforeUnmount(() => {
  clearInterval(timer.value)
})

</script>
<template>
  <el-form :model="form" label-width="120px" style="margin-top: 30px;" ref="formRef" :rules="rules"
           v-loading="resLoading">
    <el-row type="flex" justify="center">
      <el-col :span="9" :xs="24">
        <el-form-item label="账号名" prop="username">
          <el-input v-model="form.username" placeholder="账号名" :disabled="routeType === 'info'"/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center" v-if="!userId">
      <el-col :span="9" :xs="24">
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" show-password placeholder="密码"
                    :disabled="routeType === 'info'"/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center">
      <el-col :span="9" :xs="24">
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="手机号码" :disabled="routeType === 'info'"/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center">
      <el-col :span="9" :xs="24">
        <el-form-item label="姓名" prop="realname">
          <el-input v-model="form.realname" placeholder="姓名" :disabled="routeType === 'info'"/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center" v-if="isAdmin">
      <el-col :span="9" :xs="24">
        <el-form-item label="角色权限" prod="role_id">
          <el-select v-model="form.role_id" style="width: 100%;" multiple :disabled="routeType === 'info'"  @change="handleRoles">
            <el-option v-for="item in roleData" :label="item.name" :value="item.id" :key="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center" v-if="isAdmin && marketRole">
      <el-col :span="9" :xs="24">
        <el-form-item label="可见学生来源" prop="channel_ids">
          <el-select v-model="form.channel_ids" style="width: 100%;" multiple :disabled="routeType === 'info'">
            <el-option v-for="item in optionsBox.laiyuan_list" :label="item.name" :value="item.value" :key="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center" v-if="isAdmin && form.id">
      <el-col :span="9" :xs="24">
        <el-form-item label="所属项目成员" prod="role_id">
          <router-link v-for="(item,index) in form.project_list" :key="index"
                       style="color: #409EFF"
                       :to="{path:'/school-management/edit-project',query:{id:item.id,type:'edit'}}"
          >
              <span class="data-list">
                  {{ item.name }}
              </span>
            /
          </router-link>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center" v-if="isAdmin && form.id">
      <el-col :span="9" :xs="24">
        <el-form-item label="项目微信通知" prod="role_id">
          <router-link v-for="(item,index) in form.notification" :key="index"
                       style="color: #409EFF"
                       :to="{path:'/school-management/edit-project',query:{id:item.id,type:'edit'}}"
          >
              <span class="data-list">
                  {{ item.name }}
              </span>
            /
          </router-link>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center">
      <el-col :span="9" :xs="24">
        <el-form-item label="邮箱绑定" prop="email">
          <el-input v-model="form.email" placeholder="邮箱绑定" :disabled="routeType === 'info'"/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center" v-if="form.id">
      <el-col :span="9" :xs="24">
        <el-form-item label="微信解绑:" v-if="!form.qr_url">
          <el-button plain size="small" type="primary" style="cursor: pointer;" @click="handleUnbundle">解绑</el-button>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center" v-if="form.id">
      <el-col :span="9" :xs="24">
        <el-form-item label="微信绑定:">
          <el-image
              v-if="form.qr_url"
              style="width: 100px; height: 100px"
              :src="form.qr_url"
          ></el-image>
          <span v-if="!form.qr_url">
              已绑定
            </span>
          <el-button text style="cursor: pointer;margin-left: 20px;color:#409EFF;" v-if="!form.qr_url"
                     @click="handleSendMessage"
          >测试发送消息
          </el-button>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center">
      <el-col :span="9" :xs="24">
        <el-form-item>
          <el-button v-if="routeType !== 'info'" :loading="loading" type="primary" @click="onSubmit">保存</el-button>
          <el-button @click="goBack" :disabled="false">返回</el-button>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>